import _ from 'lodash'

let config = {
  permission: { 'a': { 'cu': { 'u': 'r', 'c': 'r' }, 'd': 'r' } },
  roles: ['superAdmin', 'owner', 'master', 'developer', 'guest', 'none'],
  resources: {
    application: ['a', 'a', 'u', 'r', 'r', 'n'],
    memberOwner: ['a', 'r', 'r', 'r', 'r', 'n'],
    member: ['a', 'a', 'a', 'r', 'r', 'n'],
    dictionary: ['a', 'a', 'a', 'a', 'r', 'n'],
    connect: ['a', 'a', 'a', 'a', 'r', 'n'],
    interface: ['a', 'a', 'a', 'a', 'r', 'n'],
    page: ['a', 'a', 'a', 'a', 'r', 'n'],
    menu: ['a', 'a', 'a', 'a', 'r', 'n'],
    dependence: ['a', 'a', 'a', 'a', 'r', 'n'],
    validateRule: ['a', 'a', 'a', 'a', 'r', 'n']
  }
}
const parsePermission = (config) => {
  let permission = config.permission
  let permissionDetails = {}
  const getAllPermissions = p => {
    let all = []
    _.each(p, (v, k) => {
      all.push(k)
      if (typeof v === 'object') {
        let allChildren = getAllPermissions(v)
        all = all.concat(allChildren)
        if (permissionDetails[k]) {
          permissionDetails[k] = permissionDetails[k].concat(allChildren)
        } else {
          permissionDetails[k] = [k, ...allChildren]
        }
      } else {
        all.push(v)
        if (permissionDetails[k]) {
          permissionDetails[k].push(v)
        } else {
          permissionDetails[k] = [k, v]
        }
        if (!permissionDetails[v]) {
          permissionDetails[v] = [v]
        }
      }
    })
    return _.uniq(all)
  }
  getAllPermissions(permission)
  _.each(permissionDetails, (v, k) => {
    permissionDetails[k] = _.uniq(v)
  })
  return permissionDetails
}

const parseResource = (config, permissionDetails) => {
  let resources = config.resources
  let roles = config.roles
  let res = {}
  roles.forEach((role, index) => {
    let obj = {}
    _.each(resources, (v, k) => {
      obj[k] = permissionDetails[v[index]] || []
    })
    res[role] = obj
  })
  return res
}

const Permission = parseResource(config, parsePermission(config))
export default function a(role, resource, checkPermission) {
  let rolePermission = Permission[role][resource]
  return _.uniq(rolePermission.concat(checkPermission)).length === rolePermission.length
}
